package infrastructure.configuration;

import infrastructure.exceptions.ServerFataError;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


/**
 * THis class is a signleton whih provides all configurations of the system
 * @author sashas
 *
 */
public final class Configuration implements ConfigurationProperties{

	/** Keeps file name used to save the configurations*/
	private static final String CONFIGURATION_FILE_NAME = ".properties";
	
	/** Keeps actual configuration instance*/
	private static Configuration _theConfiguration = new Configuration(CONFIGURATION_FILE_NAME);
	
	/** Keeps table of the system configurations*/
	private Properties actualConfig;
	
	/**
	 * This ctor tries to load the properties from the file, 
	 * if loading failes, it writes to the standart error that loading is failed .. 
	 * and tris to create empty properties file. in case that it fails to do this ...
	 * The the method tries to read the configuration file .. and if some error occures at this point .. the {@link ServerFataError}
	 * is thrown 
	 * {@link ServerFataError} is thrown
	 * @param propertyFileName - file name of the properties file 
	 */
	protected Configuration(String propertyFileName){
		FileReader reader = null;
		try{
			reader = new FileReader(propertyFileName);				
		}catch(FileNotFoundException ex){
			System.err.println("Configuration file '" + propertyFileName + "' not found .. trying to create");
						
		  try{
				reader = new FileReader(createNewConfigurationFile(propertyFileName));
				
			}catch(IOException fatalEx){
				throw new ServerFataError("Failed to load configuration file '" + propertyFileName + "' ", fatalEx);
			}						
		}
	
		try{
			actualConfig = new Properties();
			actualConfig.load(reader);		
		}catch(IOException ex){
			throw new ServerFataError("Failed to read configuration file'" + propertyFileName + "'", ex);
		}		
	}
	
	/**
	 * This method creates new cpnfiguration file 
	 * @param configurationFileName -file name to create
	 * @return newly created file
	 * @throws IOException - in case of failure during new file creatio
	 */
	private static File createNewConfigurationFile(String configurationFileName) throws IOException{
		// try to create a file 
		File newFile= new File(configurationFileName);			
		newFile.createNewFile();		
		return newFile;
	}
	
	/**
	 * @return instance of the configuration profile
	 */
	public static Configuration getInstance(){
		return _theConfiguration;
	}
	
	/**
	 * @return file path for the database
	 */
	public String getDBFilePath(){
		return actualConfig.getProperty(PROPERTY_DB_FILE_NAME,DEFAULT_DB_NAME);
	}
	
	/**
	 * @return lof file name of the logger
	 */
	public String getLogConfigurationFileName(){
		return actualConfig.getProperty(PROPERTY_LOG_CONFIG_FILE_NAME,DEFAULT_LOG_CONFIG_FILE_NAME);
	}
	
	
}
